<template>
  <!--引用表格-->
  <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
          <!--<a-button  type="primary" preIcon="ant-design:plus-outlined"  v-auth="'user:add'" @click="handleCreate" > 新增</a-button> -->
          <a-button  type="primary" preIcon="ant-design:export-outlined" @click="handlerGenCode">生成代码</a-button>
          <a-button  type="primary" preIcon="ant-design:import-outlined" @click="handlerImportDbTable">导入数据库表</a-button>
          <a-button  type="primary" preIcon="ant-design:import-outlined" @click="handlerImportDocumentTable">导入Word中表</a-button>
          <a-dropdown v-if="selectedRowKeys.length > 0">
            <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined"></Icon>
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button>批量操作
            <Icon icon="mdi:chevron-down"></Icon>
          </a-button>
        </a-dropdown>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)"/>
      </template>
  </BasicTable>
  <!--导入数据表-->
  <ImportDbTableDrawer @register="importDbTableDrawer" @success="handlerSuccess"/>
  <!--导入Word文件中的数据表-->
  <ImportDocumentTableDrawer @register="importDocumentTableDrawer" @success="handlerSuccess"/>
  <GenCodeModal @register="registerGenCodeModal" @success="handlerSuccess"/>
  <DbTableModal @register="registerDbTableModal"/>
</template>

<script lang="ts" name="gen-table" setup>
  import {onMounted, unref, h} from "vue"
  import {BasicTable, TableAction, ActionItem} from '/@/components/Table';
  import {useDrawer} from '/@/components/Drawer';
  import ImportDbTableDrawer from './components/ImportDbTableDrawer.vue';
  import ImportDocumentTableDrawer from './components/ImportWordTableDrawer.vue';
  import DbTableModal from './components/DbTableModal.vue';
  import GenCodeModal from './components/GenCodeModal.vue';
  import {useListPage} from '/@/hooks/system/useListPage'
  import { useMessage } from '/@/hooks/web/useMessage';
  import {list, deleteGenTable, batchDeleteGenTable} from './codeGen.api';
  import {listAllDataSource} from '../datasource/datasource.api';
  import {useModal} from '/@/components/Modal';
  import {columns, searchFormSchema} from './codeGen.data';

  const { createMessage, createConfirm} = useMessage();

  const [importDbTableDrawer, {openDrawer: openImportDbTableDrawer}] = useDrawer();
  const [importDocumentTableDrawer, {openDrawer: openImportDocumentTableDrawer}] = useDrawer();
  const [registerDbTableModal, {openModal: openDbTableModal}] = useModal();
  const [registerGenCodeModal, {openModal: openGenCodeModal}] = useModal();
  // 列表页面公共参数、方法
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    designScope: 'table-list',
    tableProps: {
      title: '生成代码表',
      api: list,
      columns: columns,
      size: 'small',
      formConfig: {
        schemas: searchFormSchema,
      },
      actionColumn: {
        width: 120,
      },
      beforeFetch:(params)=>{
        return Object.assign({'column':'createTime','order':"desc"},params)
      },
    }
  })

  //注册table数据
  const [registerTable, {reload, updateTableDataRecord, getForm},{ rowSelection, selectedRowKeys }] = tableContext

  onMounted(async () => {
    // 将数据放到下拉框上
    const resp = await listAllDataSource()
    const options = unref(resp)
    if (options && options.length > 0) {
      await getForm().updateSchema({
        field: 'datasourceId',
        componentProps: {
          optionFilterProp: "label",
          showSearch: true,
          options,
        },
      });
    }
  })

  /**
   * 数据库表
   */
  function handlerImportDbTable() {
    openImportDbTableDrawer(true, {});
  }

  /**
   * 导入word中的表
   */
  function handlerImportDocumentTable() {
    createConfirm({
      iconType: 'info',
      title: 'Word文档格式要求',
      content: () => h(
        'div', {}, [
          "1. 除了数据库表格之外不能有多余的表格",
          h('br'),
          "2. 标题格式: 表说明 + 空格 + 表名(只能是英文+下划线, 其他符号被会去掉"
        ]
      ),
      onOk: () => {
        openImportDocumentTableDrawer(true, {})
      }
    })    
  }

  /**
   * 编辑
   */
  async function handleEdit(record: Recordable) {
    openDbTableModal(true, {record})
  }

  const handlerGenCode = async () => {
    const keys = selectedRowKeys.value
    console.log("selectedRowKeys: ", keys)
    if (keys.length > 1) {
      createMessage.warning("生成代码只能选择一条数据");
      return
    }
    if (!keys[0]) {
      createMessage.warn("请选择表")
      return
    }

    openGenCodeModal(true, {id: keys[0]})
  }

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteGenTable({id: record.id});
    reload()
  }

  /**
   * 操作栏
   */
   function getTableAction(record) {
    return [
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record),
      },
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
        }
      }
    ]
  }

  const batchHandleDelete = async () => {
    console.log("selectKeys: ", selectedRowKeys.value)
    await batchDeleteGenTable({ ids: selectedRowKeys.value }, reload)
    selectedRowKeys.value = []
  }

  /**
   * 下拉操作栏
   */
   function getDropDownAction(record) {
    return [
      
    ]
  }

  const handlerSuccess = () => {
    reload()
  }
</script>